package com.yst.webplugin.fieldhandler;

import com.yst.web.utils.ClassUtils;
import com.yst.webplugin.annotation.HttpInfo;
import com.yst.webplugin.annotation.Query;
import com.yst.webplugin.exception.ExceptionParam;
import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.util.*;

public class BatchModelQueryHandler implements IFieldHandler{
    @Override
    public boolean accept(Field field) {
        return Objects.nonNull(field.getAnnotation(Query.BatchModelQuery.class));
    }

    @SneakyThrows
    @Override
    public void handle(Field field, HttpInfo httpInfo) {
        Query.BatchModelQuery batchModelQuery=field.getAnnotation(Query.BatchModelQuery.class);
        Class<?> modelClass=batchModelQuery.modelQueryClass();
        Map<String,Field> fieldMap= ClassUtils.getClassFields(modelClass);
        Map<Field,Query> queryMap=new HashMap<>();
        for(Field queryField:fieldMap.values()){
            Query query=queryField.getAnnotation(Query.class);
            queryMap.put(queryField,query);
        }

        if (queryMap.isEmpty()) throw new ExceptionParam("Defined queries of BatchModelQuery is empty");

        Object result=modelClass.newInstance();
        Map<String,Object> params=httpInfo.getBodyAs(HashMap.class);
        for (Field queryField:queryMap.keySet())
        {
            try {
                Object qryResult = QueryHandler.handleQuery(queryField, httpInfo, params);
                field.set(result,qryResult);
            }
            catch (Exception e){
                throw new RuntimeException("BatchModelQueryError:"+queryField.getDeclaringClass().getName()+";"+
                        queryField.getName()+"error="+e.getMessage());
            }
        }

        httpInfo.writeResult(result);

    }
}
